__all__ = [
    #Classes
    'HTTPClient'
]

import sys
import http.cookiejar
import urllib.request
import urllib.parse

from bs4 import BeautifulSoup


class HTTPClient:

    def __init__(self, user_agent=None, cookie_file=None):
        self.opener = urllib.request.build_opener()
        # add user agent
        if user_agent is None:
            user_agent = "Mozilla/4.0 (compatible; "\
                "MSIE 8.0; Windows NT 6.1; Trident/4.0)"
        self.opener.addheaders = [("User-Agent", user_agent)]
        # add cookie handler
        if cookie_file is None:
            self.cj = None
        else:
            if cookie_file == "::memory::":
                self.cj = http.cookiejar.CookieJar()
            else:
                self.cj = http.cookiejar.MozillaCookieJar(cookie_file)
                try:
                    self.cj.load()
                except OSError:
                    self.cj.save()
                    self.cj.load()
            cjh = urllib.request.HTTPCookieProcessor(self.cj)
            self.opener.add_handler(cjh)

    def request(self, url, method="get", data=[]):
        if method == "get":
            if data:
                request_url = url + "?" + urllib.parse.urlencode(data)
            else:
                request_url = url
            request_data = None
        else:
            request_url = url
            if data:
                request_data = urllib.parse.urlencode(data).encode("utf-8")
            else:
                request_data = None
        req = urllib.request.Request(request_url, request_data)
        doc = BeautifulSoup(self.opener.open(req))
        return doc

    def save_cookie(self):
        if self.cj is not None:
            self.cj.save()
